package com.open.party.cloud.view.home.jiCengDangJian.partyService

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import cn.android.x.model.data.ResultInfo
import cn.android.x.parent.AppTitleBaseActivity
import com.open.party.cloud.R
import com.open.party.cloud.model.ZyzHuoDongEntity
import com.open.party.cloud.model.ZyzHuoDongVo
import com.open.party.cloud.model.data.LocalCache
import com.open.party.cloud.view.home.jiCengDangJian.adapter.ZyzHuoDongRequestListAdapter
import com.open.party.cloud.viewModel.ZiYuanZheViewModel
import com.sinothk.android.utils.XUtils
import com.sinothk.view.xrefresh.XRefreshLayout
import com.sinothk.view.xrefresh.listener.RefreshHandler
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.zyz_huo_dong_detail.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*

/**
 */
class ZyzHuoDongDetailActivity : AppTitleBaseActivity() {

    private var id = ""
    private var ziYuanZheVM: ZiYuanZheViewModel? = null

    override fun getLayoutResId(): Int = R.layout.zyz_huo_dong_detail

    override fun onResume() {
        super.onResume()
        EventBus.getDefault().register(this)
    }

    override fun onPause() {
        super.onPause()
        EventBus.getDefault().unregister(this)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setViewTitle("活动详情")
        id = intent.getStringExtra("id") as String
        ziYuanZheVM = ZiYuanZheViewModel()

        ziYuanZheVM!!.getHuoDongDetail(id)
        submitBtn.setOnClickListener {
            var requestId = ""
            for (item in adapterForRequestList!!.data) {
                if (item.isSelected) {
                    requestId = item.id
                }
            }

            if (XUtils.string().isEmpty(requestId)) {
                XUtils.toast().show("请先选择报名岗位")
                return@setOnClickListener
            } else {
                val vo = ZyzHuoDongVo()
                vo.requestId = requestId
                vo.userId = LocalCache.getLoginUser().id

                showLoadingDialog("正在报名...")
                ziYuanZheVM!!.huoDongSignUp(vo)
            }
        }

        initRequestListRv()

        refreshLayout.setRefreshEnable(true)
        refreshLayout.setRefreshHandler(object : RefreshHandler {
            override fun onLoadMore(refresh: XRefreshLayout?) {
            }

            override fun onRefresh(refresh: XRefreshLayout?) {
                Handler().postDelayed({
                    ziYuanZheVM!!.getHuoDongDetail(id)
                }, 500)
            }
        })
    }

    //
    private var adapterForRequestList: ZyzHuoDongRequestListAdapter? = null

    private fun initRequestListRv() {
        requestListRv.layoutManager = object : LinearLayoutManager(this) {
            //解决RecyclerView嵌套RecyclerView滑动卡顿的问题
            //如果你的RecyclerView是水平滑动的话可以重写canScrollHorizontally方法
            override fun canScrollVertically() = false
        }
        //解决数据加载不完的问题
        requestListRv.isNestedScrollingEnabled = false
        requestListRv.setHasFixedSize(true)
        //解决数据加载完成后, 没有停留在顶部的问题
        requestListRv.isFocusable = false

        adapterForRequestList = ZyzHuoDongRequestListAdapter(this)
        requestListRv.adapter = adapterForRequestList
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun eventBusCallback(result: ResultInfo<ZyzHuoDongEntity>) {
        hideLoadingDialog()

        refreshLayout.refreshComplete()

        if (id == result.eventType) {
            when (result.code) {
                ResultInfo.SUCCESS -> {
                    showView(result.data)
                }
                ResultInfo.TOKEN_OVERDUE -> {
                    // 不存在
                }
                else -> {
                    XUtils.toast().show(result.msg)
                }
            }
        } else {
            when (result.code) {
                ResultInfo.SUCCESS -> {
                    XUtils.toast().show("报名成功")
                    // 刷新界面
                    ziYuanZheVM!!.getHuoDongDetail(id)
                }
                ResultInfo.TOKEN_OVERDUE -> {
                    // 不存在
                }
                else -> {
                    XUtils.toast().show(result.msg)
                }
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun showView(data: ZyzHuoDongEntity) {

        titleTv.text = XUtils.string().getNotNullValue(data.name)

        recProgressTv.text = XUtils.string().getNotNullValue(data.recProgress)
        recNumTv.text = XUtils.string().getNotNullValue(data.recNum)


        val days = XUtils.date().getTwoDateInterval2(Date(), data.recruitEndDate)
        if (days.contains("-")) {
            lastDaysTv.text = "0天"
        } else {
            lastDaysTv.text = days
        }

        durationTv.text = XUtils.string().getNotNullValue(data.duration) + "小时"
        scoreTv.text = "${data.score}个"
        browseTimesTv.text = "${data.browseTimes}次"

        createTimeTv.text = XUtils.date().getDateStrByDate(data.createTime, "yyyy年MM月dd日")
        perNumTv.text = "${data.perNum}人"

        orgNameTv.text = data.orgName
        userNameTv.text = XUtils.string().getNotNullValue(data.orgDTO.linkPerson)
        createPhoneTv.text = XUtils.string().getNotNullValue(data.orgDTO.linkPhone)
        emailTv.text = XUtils.string().getNotNullValue(data.orgDTO.email)

        if (!XUtils.string().isEmpty(data.img)) {
            Picasso.get().load(data.img)
                .error(R.drawable.icon_default_img)
                .placeholder(R.drawable.icon_default_img)
                .into(imageView)
            imageView.visibility = View.VISIBLE
        } else {
            imageView.visibility = View.GONE
        }

        descriptionTv.text = XUtils.string().getNotNullValue(data.description, "暂无描述 ...")

        when (data.recStatus) {
            "已结束" -> { // 报名结束
                if (data.isInActivity) {// 已参加

                    if (data.isFinishFlag) {
                        // 活动结束
                        submitBtn.visibility = View.GONE
                        requestView.visibility = View.GONE
                        signInBtn.visibility = View.GONE
                    } else {
                        submitBtn.visibility = View.GONE
                        requestView.visibility = View.GONE

                        signInBtn.visibility = View.VISIBLE
                        signInBtn.setOnClickListener {
                            XUtils.intent().openActivity(this@ZyzHuoDongDetailActivity, ZyzKaoQingMainActivity::class.java)
                                .putStringExtra("activityId", id)
                                .requestCode(100)
                                .start()
                        }
                    }
                } else {
                    submitBtn.visibility = View.GONE
                    requestView.visibility = View.GONE
                    signInBtn.visibility = View.GONE
                }
            }
            else -> {// 报名未结束
                if (data.isInActivity) {
                    submitBtn.visibility = View.GONE
                    requestView.visibility = View.GONE

                    signInBtn.visibility = View.VISIBLE
                    signInBtn.setOnClickListener {
                        XUtils.intent().openActivity(this@ZyzHuoDongDetailActivity, ZyzKaoQingMainActivity::class.java)
                            .putStringExtra("activityId", id)
                            .requestCode(100)
                            .start()
                    }
                } else {
                    submitBtn.visibility = View.VISIBLE
                    adapterForRequestList!!.setData(data.requestDTOList!!)
                    requestView.visibility = View.VISIBLE

                    signInBtn.visibility = View.GONE
                }
            }
        }
    }
}